package com.tfleo.mealssenger.adapter;

import java.util.List;

import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.UserActivity;
import com.tfleo.mealssenger.object.Comment;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;

public class CommentListAdapter extends ArrayAdapter<Comment> {
	private LayoutInflater mInflater;
	private Context mContext;
	
	public CommentListAdapter(Context context, int resource, int textViewResourceId, 
			List<Comment> objects, LayoutInflater inflater) {
		super(context, resource, textViewResourceId, objects);
		mInflater = inflater;
		mContext = context;
	}
	
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {   
		ViewHolder holder = null;
		TextView name = null;
		TextView date = null;
		TextView comment = null;
		RatingBar rating = null;
		
		final Comment comments = getItem(position);
		//ImageDownloader imageDownloader = new ImageDownloader();
		
		if(convertView == null) {
			convertView = mInflater.inflate(R.layout.comment_list_entry, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}

		holder = (ViewHolder) convertView.getTag();
		
		name = holder.getNameView();
		name.setText(comments.fromUserName);
		name.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	Intent i = new Intent(mContext, UserActivity.class);
	        	i.putExtra(UserActivity.WHO, UserActivity.NOT_FRIEND);
	        	i.putExtra("id", comments.fromUserId);
            	mContext.startActivity(i); 
	        }
	    });
		
		date = holder.getDateView();
		date.setText(comments.date);
		
		comment = holder.getCommentView();
		comment.setText(comments.content);
		
		rating = holder.getRatingView();
		rating.setRating(comments.rating);

		return convertView;
	}
	
	private class ViewHolder {
		private View vRow;
		private TextView vName = null;
		private TextView vDate = null;
		private TextView vComment = null;
		private RatingBar vRating = null;

		public ViewHolder(View row) {
			vRow = row;
		}

		public TextView getNameView() {
			if (vName == null) {
				vName = (TextView) vRow.findViewById(R.id.name);
			}
			return vName;
		}

		public TextView getDateView() {
			if (vDate == null) {
				vDate = (TextView) vRow.findViewById(R.id.date);
			}
			return vDate;
		}
		
		public TextView getCommentView() {
			if (vComment == null) {
				vComment = (TextView) vRow.findViewById(R.id.comment);
			}
			return vComment;
		}
		
		public RatingBar getRatingView() {
			if(vRating == null) {
				vRating = (RatingBar) vRow.findViewById(R.id.rating);
			}
			return vRating;
		}
	}
}
